<template>
  <basic-dialog
    :visible="visible"
    min-width="864px"
    is-show-basic-footer
    @close="handleClose"
    @submit="handleOk"
    :loading="loading"
    title="批量创建网关ID">
    <q-card-section class="margin-b-10">
      <q-table
        style="height: 400px"
        :data="tableData"
        :columns="columns"
        row-key="id"
        hide-bottom
        class="stick-last-col"
        separator="cell"
        no-data-label="暂无数据"
        color="primary"
        :pagination="pagination"
      >
        <template v-slot:body-cell-gatewaySN="{ row }">
          <q-td>
            <q-input
              dense
              border
              outlined
              :disable="row.disabled"
              ref="rule"
              class="q-ml-sm q-mr-sm"
              v-model.trim="row.gatewaySN"
              style="width:220px;height:44px"
            />
          </q-td>
        </template>
        <template v-slot:body-cell-productSN="{row}">
          <q-td>
            <q-select class="select"
                      outlined
                      style="width:180px"
                      dense
                      :disable="row.disabled"
                      emit-value
                      map-options
                      options-dense
                      :options="products"
                      v-model="row.productSN">
            </q-select>
          </q-td>
        </template>
        <template v-slot:body-cell-operations="props">
          <q-td class="operations" style="width: 100px">
            <q-btn flat dense round color="primary" icon="iconfont icontubiao-12" @click="editCreate(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn flat dense round color="primary" icon="iconfont icontubiao-16" @click="deleteCreate(props.row)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
      <div class="add-wrapper" v-if="showAddIcon" @click="addCreate">
        <q-icon name="iconfont icontubiao-39" class="margin-r-10"/>
        添加
      </div>
    </q-card-section>
  </basic-dialog>
</template>

<script>
// eslint-disable-next-line import/named
import { createPatchBox, getPlcProducts } from '../../../../boot/miot/plc-list'

export default {
  name: 'patch-create-gateway',
  data () {
    return {
      visible: false,
      tableData: [],
      columns: [
        { name: 'gatewaySN', label: '网关序列号', align: 'center', field: 'gatewaySN' },
        { name: 'productSN', label: '网关型号', align: 'center', field: 'productSN' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ],
      pagination: {
        rowsPerPage: 0
      },
      products: [],
      loading: false
    }
  },
  computed: {
    showAddIcon () {
      return this.tableData.length < 51
    }
  },
  created () {
    this.getPlcProductInfo()
  },
  methods: {
    showDialog () {
      this.visible = true
    },
    handleClose () {
      this.visible = false
    },
    handleOk () {
      if (!this.checkData()) {
        this.$message.error('请完善输入内容')
        return
      }
      const result = this.tableData.map(item => ({
        gatewaySN: item.gatewaySN,
        productSN: item.productSN,
        productName: this.products.find(product => product.value === item.productSN)?.label
      }))
      this.loading = true
      createPatchBox(result).then(res => {
        if (res.data.length > 0) {
          this.$message.warning(`${res.data.length}条数据创建失败，请检查网关序列号是否正确`)
          this.tableData = this.tableData.filter(item => {
            const index = res.data.findIndex(err => item.gatewaySN === err)
            return index !== -1
          })
        } else {
          this.tableData = []
        }
        this.visible = false
        this.$emit('success')
      }).finally(() => {
        this.loading = false
      })
    },
    addCreate () {
      if (!this.checkData()) {
        this.$message.error('请完善输入内容')
        return
      }
      const id = '__' + Math.random().toString(36).substr(2, 9)
      const rowData = {
        id,
        disabled: false,
        gatewaySN: '',
        productSN: null,
        gateWayType: null
      }
      this.tableData.push(rowData)
    },
    editCreate (row) {
      this.tableData.forEach(item => {
        item.disabled = true
      })
      row.disabled = false
    },
    deleteCreate (row) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>确认删除该条信息吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        const index = row.__index
        this.tableData.splice(index, 1)
      })
    },
    // 校验数据
    checkData () {
      return this.tableData.every(item => {
        if (item.productSN && item.productSN) {
          item.disabled = true
          return true
        }
        return false
      })
    },
    // 获取产品列表
    async getPlcProductInfo () {
      const { data } = await getPlcProducts()
      if (data?.length) {
        this.products = data.map(item => ({
          label: item.productName,
          value: item.productSN
        }))
      }
    }
  }
}
</script>

<style scoped lang="scss">
.add-wrapper{
  width: 100%;
  height: 48px;
  background: #F3F3F3;
  border-radius: 0px 0px 6px 6px;
  font-size: 14px;
  font-weight: 500;
  color: #5F77FD;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>
